package org.jsbd.boss.timer;

import org.jsbd.boss.dao.INewWeiboUserDao;
import org.jsbd.boss.domian.channel.ThirdUserQueryVo;
import org.jsbd.boss.domian.channel.WeiboUser;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class INewWeiboUserTaskTimer extends TaskAdapterHandler {
    public static final Logger LOGGER = LoggerFactory.getLogger(INewWeiboUserTaskTimer.class);

    @Resource
    private INewWeiboUserDao newWeiboUserDao;

    /*
     * (non-Javadoc)
     *
     * @see org.jsbd.boss.timer.TaskHandler#execute()
     */
    @Override
    public void run() {
        String lock = CacheKey.NEW_WEIBO_USER_LOCK;
        if (redisClient.evalSetNx(lock, 120)) {
            long now = System.currentTimeMillis();

            Long queueSize = redisClient.getQueueSize(CacheKey.NEW_WEIBO_USER_QUEUE);

            if (queueSize > 50) {
                redisClient.expire(lock, 3000);
                return;
            }

            Integer index = (Integer) redisClient.get(CacheKey.NEW_WEIBO_USER_INDEX);

            if (index == null) {
                index = 5835077;
            }

            ThirdUserQueryVo thirdUserQueryVo = new ThirdUserQueryVo();
            thirdUserQueryVo.setStart(index);
            thirdUserQueryVo.setLength(100);
            List<WeiboUser> weiboUsers = newWeiboUserDao.selectUserList(thirdUserQueryVo);

            for (WeiboUser weiboUser : weiboUsers) {
                Integer id = weiboUser.getId();
                if (id < index) {
                    index = id;
                }
                redisClient.putToQueue(CacheKey.NEW_WEIBO_USER_QUEUE, weiboUser);
            }
            redisClient.put(CacheKey.NEW_WEIBO_USER_INDEX, index);
            LOGGER.warn("微博新用户更新花费时间{}秒", ((System.currentTimeMillis() - now) / 1000));
            redisClient.expire(lock, 3000);
        }

    }


}
